package org.baeta.client;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientResponse;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Implementation of Webservice client for country information.
 *
 * @author <a href="mailto:rui.baeta@gmail.com">Rui Baeta</a>
 */
public class CountryInfoJSONClient extends AbstractClient implements CountryInfoClient
{
    private static final Log LOG = LogFactory.getLog(CountryInfoJSONClient.class);

    @Override
    public JSONObject getCountryInfo(String countryCode) throws Exception
    {
        JSONObject jsonObject = null;
        try
        {
            ClientRequest request = buildRequest(String.format("http://api.geonames.org/countryInfoJSON?lang=pt&country=%s&username=rui.baeta&style=full", countryCode));

            LOG.debug(String.format("Requesting rest ws at uri [%s]...", request.getUri()));
            ClientResponse<String> response = request.get(String.class);

            if (response.getStatus() != 200)
            {
                throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(response.getEntity().getBytes())));
            JSONTokener tokener = new JSONTokener(br);
            jsonObject = new JSONObject(tokener);

        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        }

        return jsonObject;
    }

}
